package org.numb.web.bussiness.initdb.service;

import com.alibaba.druid.DbType;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import com.alibaba.druid.sql.parser.SQLParserUtils;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringBufferInputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import org.apache.commons.io.FileUtils;
import org.numb.web.bussiness.initdb.domain.aggregate.DDLStatement;
import org.numb.web.bussiness.initdb.domain.valobj.DBConfiguration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class DDLInitService implements InitService {

    private static final PathMatchingResourcePatternResolver RESOURCE_PATTERN_RESOLVER =
        new PathMatchingResourcePatternResolver();

    @Resource
    private DBConfiguration dbConfiguration;

    @PostConstruct
    public boolean init() {

        return true;
    }

    @Override
    public boolean execute() {
        return false;
    }

    public List<DDLStatement> parseDDL(String path) throws IOException {
        org.springframework.core.io.Resource[] resources = RESOURCE_PATTERN_RESOLVER.getResources(path);
        List<DDLStatement> ddlStatements = new ArrayList<>();
        for (org.springframework.core.io.Resource resource : resources) {
            String sql = FileUtils.readFileToString(resource.getFile(), StandardCharsets.UTF_8);
            DDLStatement ddlStatement = new DDLStatement(resource.getFile().getName(),
                SQLUtils.parseStatements(sql, DbType.valueOf(dbConfiguration.getDbType())));
            ddlStatements.add(ddlStatement);
        }
        return ddlStatements;
    }

}
